<?php
namespace Api\Controller;
use Think\Controller;
/**
 * 企业微信接口类
 * User: 咩咩
 * Date: 2019/2/18
 * Time: 14:51
 */
class QiYeApiController extends Controller{
    //CorpID(企业ID-蓝月亮的世界)
    protected $corpid = "wx36ef368cf28caea0";
    //CorpSecret(应用密钥-网页授权)
    protected $corpsecret = "3mCYMxjEoxyHhyGUAv1nKK-o6uPjUo-NO3Zyw_7ZoqA";

    /**
     * 首页调试
     */
    public function index(){
//        /**
//         * 微信测试模式
//         */
//        $redirect_uri=U('Api/QiYeApi/index','','',true);//设置回调页面
//        $UserInfo = $this->getUser($this->corpid,$redirect_uri);
//
//        echo $UserInfo['qr_code'];

//        $time = date('Y-m-d H:i:s');
//        error_log('$time='.$time."\n", 3, "test.log");//打印日志
    }

    /**
     * 获取access_token
     */
    public function getAccessToken(){
        $code_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$this->corpid."&corpsecret=".$this->corpsecret;
        $access_token_str = $this->curl_get($code_url);
        $access_token_list = json_decode($access_token_str, true);
        if ($access_token_list['errcode'] == 0) {
            return $access_token_list["access_token"];
        }
        return false;
    }

    /**
     * 企业微信H5分享-JS-SDK使用权限签名接口
     * string  url  当前链接的url
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      签名数组
     */
    public function jsapi_ticket(){
        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        //注意:URL一定要动态获取，不能hardcode
        $url = I('post.url');
//        error_log('$url='.$url."\n", 3, "test.log");//打印日志
        if(!$url){
            $de_res['msg'] = '缺少url参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $timestamp = time();
        /*判断access_token 获取jsapi_ticket*/
        if($_SESSION['jsapi']['jsapi_ticket'] && $_SESSION['jsapi']['access_token'] && $_SESSION['jsapi']['expire_time'] > $timestamp){
            /*获取jsapi_ticket*/
            $jsapiTicket = $_SESSION['jsapi']['jsapi_ticket'];
//            error_log('$_SESSION='.json_encode($_SESSION, true)."\n", 3, "test.log");//打印日志
        }else{
            /*获取access_token*/
            if($_SESSION['jsapi']['access_token'] && $_SESSION['jsapi']['expire_time'] > $timestamp){
                $access_token = $_SESSION['jsapi']['access_token'];
//            error_log('$_SESSION='.json_encode($_SESSION, true)."\n", 3, "test.log");//打印日志
            }else{
                $access_token = $this->getAccessToken();
//            error_log($access_token."\n", 3, "test.log");//打印日志
                if($access_token == false){
                    $de_res['msg'] = 'AccessToken获取失败';
                    $de_res['error'] = 401;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }
                //将获取到的aceess_token存到session
                $_SESSION['jsapi']['access_token'] = $access_token;
                $_SESSION['jsapi']['expire_time'] = $timestamp + 7000;
            }

            /*获取jsapi_ticket*/
            $jsapi_ticket_url='https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token='.$access_token;
            $res = $this->curl_get($jsapi_ticket_url);
//            error_log('$res='.$res."\n", 3, "test.log");//打印日志
            $result = json_decode($res, true);
            //当错误码不为0时，返回错误
            if($result['errcode'] != 0){
                $de_res['msg'] = $result['errmsg'];
                $de_res['error'] = $result['errcode'];
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }

            $jsapiTicket = $result['ticket'];
            //将重新获取到的jsapi_ticket存到session
            $_SESSION['jsapi']['jsapi_ticket'] = $jsapiTicket;
        }

        //获取随机字符串
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
//        error_log('$jsapi_ticket='.$jsapiTicket."\n", 3, "test.log");//打印日志
//        error_log('$nonceStr='.$nonceStr."\n", 3, "test.log");//打印日志
//        error_log('$timestamp='.$timestamp."\n", 3, "test.log");//打印日志
//        error_log('$url='.$url."\n", 3, "test.log");//打印日志
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
//        error_log('$string='.$string."\n", 3, "test.log");//打印日志
        $signature = sha1($string);
//        error_log('$signature='.$signature."\n", 3, "test.log");//打印日志

        $signPackage = array(
            "appid"     => $this->corpid,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );

        $de_res['data'] = $signPackage;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * JS-SDK签名用于生成随机字符串
     */
    public function createNonceStr($length = 16){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 企业微信H5端-授权登录获取用户信息接口
     * string  code  Code参数
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      用户信息列表
     */
    public function getQYUserInfo(){
        $db_wash_qy_user = M('wash_qy_user');//实例化企业用户信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $code = I('post.code');
//        error_log($code."\n", 3, "test.log");//打印日志
        if(!$code){
            $de_res['msg'] = '缺少code参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $timestamp = time();
        /*获取access_token*/
        if($_SESSION['jsapi']['access_token'] && $_SESSION['jsapi']['expire_time'] > $timestamp){
            $access_token = $_SESSION['jsapi']['access_token'];
//            error_log('$_SESSION='.json_encode($_SESSION, true)."\n", 3, "test.log");//打印日志
        }else{
            $access_token = $this->getAccessToken();
//            error_log($access_token."\n", 3, "test.log");//打印日志
            if($access_token == false){
                $de_res['msg'] = 'AccessToken获取失败';
                $de_res['error'] = 401;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
            //将重新获取到的aceess_token存到session
            $_SESSION['jsapi']['access_token'] = $access_token;
            $_SESSION['jsapi']['expire_time'] = $timestamp + 7000;
        }

        //获取UserId
        $get_user_id_url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$access_token.'&code='.$code;
        $code_str = $this->curl_get($get_user_id_url);
//        error_log($code_str."\n", 3, "test.log");//打印日志
        $code_list = json_decode($code_str, true);
        $UserId_list = $code_list;
        //当错误码不为0时，返回错误
        if($UserId_list['errcode'] != 0){
            $de_res['msg'] = $UserId_list['errmsg'];
            $de_res['error'] = $UserId_list['errcode'];
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $UserId = $UserId_list['UserId'];

        //获取成员信息
        $get_user_info_url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='.$access_token.'&userid='.$UserId;
        $code_str = $this->curl_get($get_user_info_url);
//            error_log($code_str."\n", 3, "test.log");//打印日志
        $code_list = json_decode($code_str, true);
        $UserInfo = $code_list;
        //当错误码不为0时，返回错误
        if($UserInfo['errcode'] != 0){
            $de_res['msg'] = $UserInfo['errmsg'];
            $de_res['error'] = $UserInfo['errcode'];
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $qy_user = $db_wash_qy_user->where("userid='$UserId'")->field('id')->find();
        if($qy_user){
            //更新企业用户信息表
            $info['name'] = $UserInfo['name'];
            $info['gender'] = $UserInfo['gender'];
            $info['avatar'] = $UserInfo['avatar'];
            $info['update_time'] = date('Y-m-d H:i:s');
            $edit_wash_qy_user = $db_wash_qy_user->where("userid='$UserId'")->setField($info);
            if(!$edit_wash_qy_user){
                $de_res['msg'] = '更新企业用户信息失败';
                $de_res['error'] = 402;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
        }else{
            //写入企业用户信息表
            $info['userid'] = $UserInfo['userid'];
            $info['name'] = $UserInfo['name'];
            $info['gender'] = $UserInfo['gender'];
            $info['avatar'] = $UserInfo['avatar'];
            $info['create_time'] = date('Y-m-d H:i:s');
            $info['update_time'] = date('Y-m-d H:i:s');
            $add_wash_qy_user = $db_wash_qy_user->data($info)->add();
            if(!$add_wash_qy_user){
                $de_res['msg'] = '添加企业用户信息失败';
                $de_res['error'] = 402;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
        }

        $de_res['data'] = $UserInfo;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 企业微信H5端-二维码看板接口
     * string   userid       企业用户编号
     * int      type         类型 1全部 2已绑定 3已提交 4已退货
     * string   datetime     时间(格式1900-01-01)
     * int      page_num     第几页
     * int      page_size    每页显示条数
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      count 总数
     *      list  二维码信息列表
     */
    public function qrcode_list(){
        $db_wash_qrcode = M('wash_qrcode');//实例化二维码信息表
        $db_wash_consumer_product = M('wash_consumer_product');//实例化SFA商品列表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array('count'=>'0','list'=>array()));

        $userid = I('post.userid');
        if(!$userid){
            $de_res['msg'] = '缺少userid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $type = I('post.type');
        if(!$type){
            $de_res['msg'] = '缺少type参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        if($type == 1){//全部
        }elseif($type == 2){//已绑定
            $where['status'] = 1;
        }elseif($type == 3){//已提交
            $where['status'] = 2;
        }elseif($type == 4){//已退货
            $where['status'] = 3;
        }else{
            $de_res['msg'] = 'type参数错误';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $datetime = I('post.datetime');
        if(!$datetime){
            $de_res['msg'] = '缺少datetime参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }else{
            $where['update_time'] = array('like', "$datetime%");
        }

        $page_num = I('post.page_num');
        if(!$page_num){
            $de_res['msg'] = '缺少page_num参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $page_size = I('post.page_size');
        if(!$page_size){
            $de_res['msg'] = '缺少page_size参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $where['qy_uid'] = $userid;
        $qrcode_list = $db_wash_qrcode->where($where)->order('update_time DESC')->field('p_id,qrcode_id,status,update_time')->select();
        if($qrcode_list){
            //查询总数
            $qrcode_list_count = $db_wash_qrcode->where($where)->count();
            $de_res['data']['count'] = $qrcode_list_count;

            $arr = array();
            foreach($qrcode_list as $qrcode){
                $p_id = $qrcode['p_id'];
                $product = $db_wash_consumer_product->where("p_id='$p_id'")->field('name,img_url')->find();
                if($product){
                    $qrcode['name'] = $product['name'];
                    $qrcode['img_url'] = $product['img_url'];
                    array_push($arr,$qrcode);
                }
            }

            //分页
            $de_res['data']['list'] = $this->page_array($page_size,$page_num,$arr,0);
        }

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 企业微信H5端-扫一扫接口
     * string   qrcode_id   二维码编号
     * string   userid      企业用户编号
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      二维码信息
     */
    public function scan(){
        $db_wash_qrcode = M('wash_qrcode');//实例化二维码信息表
        $db_wash_pici = M('wash_pici');//实例化二维码批次表
        $db_wash_consumer_product = M('wash_consumer_product');//实例化SFA商品列表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $qrcode_id = I('post.qrcode_id');
        if(!$qrcode_id){
            $de_res['msg'] = '缺少qrcode_id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $userid = I('post.userid');
        if(!$userid){
            $de_res['msg'] = '缺少userid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $where['qrcode_id'] = $qrcode_id;
        $qrcode_info = $db_wash_qrcode->where($where)->field('p_id,pici_id,qrcode_id,status,qy_uid')->find();
        if($qrcode_info){
            $status = $qrcode_info['status'];
            $qy_uid = $qrcode_info['qy_uid'];
            $p_id = $qrcode_info['p_id'];
            $pici_id = $qrcode_info['pici_id'];
            if($status == 0){
                $de_res['data']['qrcode_id'] = $qrcode_id;
                $de_res['data']['p_id'] = $p_id;

                $product = $db_wash_consumer_product->where("p_id='$p_id'")->field('name,img_url')->find();
                if($product){
                    $de_res['data']['name'] = $product['name'];
                    $de_res['data']['img_url'] = $product['img_url'];
                }

                $pici = $db_wash_pici->where("p_id='$p_id' AND pici_id='$pici_id'")->field('pici_name')->find();
                if($pici){
                    $de_res['data']['pici_name'] = $pici['pici_name'];
                }
            }else{
                if($userid == $qy_uid){
                    $de_res['msg'] = '您已绑定该二维码！';
                    $de_res['error'] = 4021;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }else{
                    $de_res['msg'] = '该二维码已经绑定其他促销员！';
                    $de_res['error'] = 4022;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }
            }
        }else{
            $de_res['msg'] = '请扫描有效二维码';
            $de_res['error'] = 4011;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 企业微信H5端-绑定接口
     * string   qrcode_id   二维码编号
     * string   userid      企业用户编号
     * string   bangding_end_time   过期时间（格式1900-01-01 23:59:59）
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function bind(){
        $db_wash_qrcode = M('wash_qrcode');//实例化二维码信息表
        $db_wash_pici = M('wash_pici');//实例化二维码批次表

        //返回值数组
        $de_res = array('msg'=>'绑定成功！', 'error'=> 0, 'data'=> array());

        $qrcode_id = I('post.qrcode_id');
        if(!$qrcode_id){
            $de_res['msg'] = '缺少qrcode_id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $userid = I('post.userid');
        if(!$userid){
            $de_res['msg'] = '缺少userid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $bangding_end_time = I('post.bangding_end_time');
        if(!$bangding_end_time){
            $de_res['msg'] = '缺少bangding_end_time参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $where['qrcode_id'] = $qrcode_id;
        $qrcode_info = $db_wash_qrcode->where($where)->field('p_id,pici_id,qrcode_id,status,qy_uid')->find();
        if($qrcode_info){
            $status = $qrcode_info['status'];
            $qy_uid = $qrcode_info['qy_uid'];
            $p_id = $qrcode_info['p_id'];
            $pici_id = $qrcode_info['pici_id'];
            if($status == 0){
                //更新二维码信息表
                $info['qy_uid'] = $userid;
                $info['status'] = 1;
                $info['bangding_time'] = date('Y-m-d H:i:s');
                $info['bangding_end_time'] = $bangding_end_time;
                $info['update_time'] = date('Y-m-d H:i:s');
                $edit_wash_qrcode = $db_wash_qrcode->where("qrcode_id='$qrcode_id'")->setField($info);
                if(!$edit_wash_qrcode){
                    $de_res['msg'] = '更新二维码信息失败';
                    $de_res['error'] = 4031;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }
                //更新二维码批次表
                $pici_info['update_time'] = date('Y-m-d H:i:s');
                $edit_wash_pici = $db_wash_pici->where("p_id='$p_id' AND pici_id='$pici_id'")->setField($pici_info);
                if(!$edit_wash_pici){
                    $de_res['msg'] = '更新批次信息失败';
                    $de_res['error'] = 4032;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }
                $inc_wash_pici = $db_wash_pici->where("p_id='$p_id' AND pici_id='$pici_id'")->setInc('cuxiao_num');
                if(!$inc_wash_pici){
                    $de_res['msg'] = '更新批次信息失败';
                    $de_res['error'] = 4033;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }
            }else{
                if($userid == $qy_uid){
                    $de_res['msg'] = '您已绑定该二维码！';
                    $de_res['error'] = 4021;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }else{
                    $de_res['msg'] = '该二维码已经绑定其他促销员！';
                    $de_res['error'] = 4022;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }
            }
        }else{
            $de_res['msg'] = '请扫描有效二维码';
            $de_res['error'] = 4011;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 企业微信H5端-解除绑定接口
     * string   qrcode_id   二维码编号
     * string   userid      企业用户编号
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function unbind(){
        $db_wash_qrcode = M('wash_qrcode');//实例化二维码信息表
        $db_wash_pici = M('wash_pici');//实例化二维码批次表

        //返回值数组
        $de_res = array('msg'=>'解绑成功！', 'error'=> 0, 'data'=> array());

        $qrcode_id = I('post.qrcode_id');
        if(!$qrcode_id){
            $de_res['msg'] = '缺少qrcode_id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $userid = I('post.userid');
        if(!$userid){
            $de_res['msg'] = '缺少userid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $where['qrcode_id'] = $qrcode_id;
        $qrcode_info = $db_wash_qrcode->where($where)->field('p_id,pici_id,qrcode_id,status,qy_uid')->find();
        if($qrcode_info){
            $status = $qrcode_info['status'];
            $p_id = $qrcode_info['p_id'];
            $pici_id = $qrcode_info['pici_id'];
            $qy_uid = $qrcode_info['qy_uid'];

            if($userid == $qy_uid){
                if($status == 1){
                    //更新二维码信息表
                    $info['qy_uid'] = null;
                    $info['status'] = 0;
                    $info['bangding_time'] = null;
                    $info['bangding_end_time'] = null;
                    $info['update_time'] = date('Y-m-d H:i:s');
                    $edit_wash_qrcode = $db_wash_qrcode->where("qrcode_id='$qrcode_id'")->setField($info);
                    if(!$edit_wash_qrcode){
                        $de_res['msg'] = '更新二维码信息失败';
                        $de_res['error'] = 4031;
                        $en_res = json_encode($de_res, 320);
                        exit($en_res);
                    }
                    //更新二维码批次表
                    $pici_info['update_time'] = date('Y-m-d H:i:s');
                    $edit_wash_pici = $db_wash_pici->where("p_id='$p_id' AND pici_id='$pici_id'")->setField($pici_info);
                    if(!$edit_wash_pici){
                        $de_res['msg'] = '更新批次信息失败';
                        $de_res['error'] = 4032;
                        $en_res = json_encode($de_res, 320);
                        exit($en_res);
                    }
                    $inc_wash_pici = $db_wash_pici->where("p_id='$p_id' AND pici_id='$pici_id'")->setDec('cuxiao_num');
                    if(!$inc_wash_pici){
                        $de_res['msg'] = '更新批次信息失败';
                        $de_res['error'] = 4033;
                        $en_res = json_encode($de_res, 320);
                        exit($en_res);
                    }
                }else{
                    $de_res['msg'] = '该二维码不可解绑';
                    $de_res['error'] = 4021;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }
            }else{
                $de_res['msg'] = '没有权限执行该操作';
                $de_res['error'] = 4022;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
        }else{
            $de_res['msg'] = '请扫描有效二维码';
            $de_res['error'] = 4011;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 企业微信H5端-自动解除绑定接口（每天0点自动执行）
     */
    public function auto_unbind(){
        $db_wash_qrcode = M('wash_qrcode');//实例化二维码信息表
        $db_wash_pici = M('wash_pici');//实例化二维码批次表

        $where['status'] = 1;
        $where['bangding_end_time'] = array('lt', date('Y-m-d 00:00:00', time()));
        $qrcode_list = $db_wash_qrcode->where($where)->field('p_id,pici_id,qrcode_id')->select();
        if($qrcode_list){
            foreach($qrcode_list as $qrcode){
                $p_id = $qrcode['p_id'];
                $pici_id = $qrcode['pici_id'];
                $qrcode_id = $qrcode['qrcode_id'];

                //更新二维码信息表
                $info['qy_uid'] = null;
                $info['status'] = 0;
                $info['bangding_time'] = null;
                $info['bangding_end_time'] = null;
                $info['update_time'] = date('Y-m-d H:i:s');
                $edit_wash_qrcode = $db_wash_qrcode->where("qrcode_id='$qrcode_id'")->setField($info);
                if(!$edit_wash_qrcode){
                    error_log("更新二维码信息失败"."\n", 3, "auto_unbind_error.log");//打印日志
                }

                //更新二维码批次表
                $pici_info['update_time'] = date('Y-m-d H:i:s');
                $edit_wash_pici = $db_wash_pici->where("p_id='$p_id' AND pici_id='$pici_id'")->setField($pici_info);
                if(!$edit_wash_pici){
                    error_log("更新批次信息失败"."\n", 3, "auto_unbind_error.log");//打印日志
                }

                $inc_wash_pici = $db_wash_pici->where("p_id='$p_id' AND pici_id='$pici_id'")->setDec('cuxiao_num');
                if(!$inc_wash_pici){
                    error_log("更新批次信息失败"."\n", 3, "auto_unbind_error.log");//打印日志
                }
            }
        }
    }

    /**
     * 企业微信H5端-退货接口
     * string   qrcode_id       二维码编号
     * string   userid          企业用户编号
     * string   tuihuo_reason   退货理由
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function return_goods(){
        $db_wash_qrcode = M('wash_qrcode');//实例化二维码信息表

        //返回值数组
        $de_res = array('msg'=>'退货成功！', 'error'=> 0, 'data'=> array());

        $qrcode_id = I('post.qrcode_id');
        if(!$qrcode_id){
            $de_res['msg'] = '缺少qrcode_id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $userid = I('post.userid');
        if(!$userid){
            $de_res['msg'] = '缺少userid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $tuihuo_reason = I('post.tuihuo_reason');
        if(!$tuihuo_reason){
            $de_res['msg'] = '缺少tuihuo_reason参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $where['qrcode_id'] = $qrcode_id;
        $qrcode_info = $db_wash_qrcode->where($where)->field('p_id,pici_id,qrcode_id,status,qy_uid')->find();
        if($qrcode_info){
            $status = $qrcode_info['status'];
            $p_id = $qrcode_info['p_id'];
            $pici_id = $qrcode_info['pici_id'];
            $qy_uid = $qrcode_info['qy_uid'];

            if($userid == $qy_uid){
                if($status == 2){
                    //更新二维码信息表
                    $info['status'] = 3;
                    $info['tuihuo_reason'] = $tuihuo_reason;
                    $info['tuihuo_time'] = date('Y-m-d H:i:s');
                    $info['update_time'] = date('Y-m-d H:i:s');
                    $edit_wash_qrcode = $db_wash_qrcode->where("qrcode_id='$qrcode_id'")->setField($info);
                    if(!$edit_wash_qrcode){
                        $de_res['msg'] = '更新二维码信息失败';
                        $de_res['error'] = 4031;
                        $en_res = json_encode($de_res, 320);
                        exit($en_res);
                    }
                }else{
                    $de_res['msg'] = '该二维码不可退货';
                    $de_res['error'] = 4021;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }
            }else{
                $de_res['msg'] = '没有权限执行该操作';
                $de_res['error'] = 4022;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
        }else{
            $de_res['msg'] = '请扫描有效二维码';
            $de_res['error'] = 4011;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 企业微信H5端-查看详情接口
     * string   qrcode_id   二维码编号
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      qrcode_id      二维码编号
     *      p_id           产品编号
     *      status         二维码当前状态（0未绑定 1已绑定 2已提交 3已退货）
     *      img_url        产品图
     *      name           产品名称
     *      pici_name      批次名称
     *      bangding_time  绑定时间（当status为1时 存在该字段）
     *      bangding_end_time  绑定有效期（当status为1时 存在该字段）
     *      nickName       消费者昵称（当status为2时 存在该字段）
     *      tijiao_time    提交时间（当status为2时 存在该字段）
     *      tuihuo_reason  退货原因（当status为3时 存在该字段）
     *      tuihuo_time    退货时间（当status为3时 存在该字段）
     */
    public function qrcode_info(){
        $db_wash_user = M('wash_user');//实例化用户信息表
        $db_wash_qrcode = M('wash_qrcode');//实例化二维码信息表
        $db_wash_pici = M('wash_pici');//实例化二维码批次表
        $db_wash_consumer_product = M('wash_consumer_product');//实例化SFA商品列表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $qrcode_id = I('post.qrcode_id');
        if(!$qrcode_id){
            $de_res['msg'] = '缺少qrcode_id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $qrcode_info = $db_wash_qrcode->where("qrcode_id='$qrcode_id'")->field('p_id,pici_id,status,bangding_time,bangding_end_time,uid,tijiao_time,tuihuo_reason,tuihuo_time')->find();
        if($qrcode_info){
            $arr['qrcode_id'] = $qrcode_id;
            $arr['p_id'] = $qrcode_info['p_id'];
            $arr['status'] = $qrcode_info['status'];
            $arr['bangding_time'] = $qrcode_info['bangding_time'];
            $arr['bangding_end_time'] = $qrcode_info['bangding_end_time'];
            $arr['tijiao_time'] = $qrcode_info['tijiao_time'];
            $arr['tuihuo_reason'] = $qrcode_info['tuihuo_reason'];
            $arr['tuihuo_time'] = $qrcode_info['tuihuo_time'];

            $p_id = $qrcode_info['p_id'];
            $pici_id = $qrcode_info['pici_id'];
            $uid = $qrcode_info['uid'];
            //查询产品信息
            $product = $db_wash_consumer_product->where("p_id='$p_id'")->field('name,img_url')->find();
            if($product){
                $arr['name'] = $product['name'];
                $arr['img_url'] = $product['img_url'];
            }
            //查询批次信息
            $pici = $db_wash_pici->where("p_id='$p_id' AND pici_id='$pici_id'")->field('pici_name')->find();
            if($pici){
                $arr['pici_name'] = $pici['pici_name'];
            }

            //查询消费者信息
            $user_info = $db_wash_user->where("uid='$uid'")->field('nickName')->find();
            if($user_info){
                $arr['nickName'] = $user_info['nickName'];
            }

            $de_res['data'] = $arr;
        }else{
            $de_res['msg'] = '二维码信息不存在';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * curl get方式
     * string  url    链接地址
     */
    public function curl_get($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }

    /**
     * curl post方式
     * string  url    链接地址
     * array   param  数组array("key1" => $value1, "key2" => $value2);
     */
    public function curl_post($url, $param)
    {
        $param = json_encode($param,true);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch);
        return $data;
    }

    /**
     * 数组分页函数(核心函数 array_slice)
     * 用此函数之前要先将数据库里面的所有数据按一定的顺序查询出来存入数组中
     * $count  每页多少条数据
     * $page   当前第几页
     * $array  查询出来的所有数组
     * order   0-不变 1-反序
     */
    public function page_array($count,$page,$array,$order){
        global $countpage; #定全局变量
        $page=(empty($page))?'1':$page; #判断当前页面是否为空 如果为空就表示为第一页面
        $start=($page-1)*$count; #计算每次分页的开始位置
        if($order==1){
            $array=array_reverse($array);
        }
        $totals=count($array);
        $countpage=ceil($totals/$count); #计算总页面数
        $pagedata=array();
        $pagedata=array_slice($array,$start,$count);
        return $pagedata;  #返回查询数据
    }
}